package com.example.practicespring.controller.serverManage;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.practicespring.controller.BaseController;
import com.example.practicespring.domain.Server;
import com.example.practicespring.domain.ServerTask;
import com.example.practicespring.service.ServerService;
import com.example.practicespring.service.ServerTaskService;
import com.example.practicespring.utils.Query;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.example.practicespring.utils.ipv4Utils.isIPv4;

@SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
@Slf4j
@RestController
@RequestMapping(value = "/serverManage")
public class ServerControl extends BaseController {

    @Resource
    private ServerService serverService;

    @Resource
    private ServerTaskService serverTaskService;

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "/serverInfo", method = RequestMethod.GET)
    public SaResult serverInfo(@RequestParam("currentPage") int pageNum,
                               @RequestParam("pageSize") int pageSize) {

        Page<Server> page = new Page<>(pageNum, pageSize);
        page = serverService.page(page, new QueryWrapper<>());

        for (Server server : page.getRecords()) {
            List<String> ipList = new ArrayList<>();
            // 使用String的split方法按逗号分割ip字段，并添加到ipList中
            String[] ipParts = server.getIp().split(",");
            for (String ipPart : ipParts) {
                ipList.add(ipPart.trim()); // 可能需要trim来去除空格
            }
            server.setIpList(ipList);

            List<String> moduleList = new ArrayList<>();
            String[] moduleParts = server.getModule().split(",");
            for (String modulePart : moduleParts) {
                 moduleList.add(modulePart.trim());
            }
            server.setModuleList(moduleList);
        }
        JSONObject data = new JSONObject();
        data.put("data", page.getRecords());
        data.put("total", page.getTotal());
        return SaResult.data(data).setMsg("服务器信息查询成功！");
    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "/addServer", method = RequestMethod.POST)
    public SaResult addServer(@RequestBody Server server) {
        if (server == null) {
            return SaResult.error("信息不存在");
        }
        // 服务器名称校验
        QueryWrapper<Server> query = new QueryWrapper<>();
        query.eq("name", server.getName());
        Server nameCheck = serverService.getOne(query);
        if (!Objects.isNull(nameCheck)) {
            return SaResult.error("服务器名称已存在");
        }
        // 服务器ip校验
        for (String ip : server.getIpList()) {

            // ipv4地址校验
            if (!isIPv4(ip)) {
                return SaResult.error("服务器ip格式错误: " + ip);
            }
            QueryWrapper<Server> checkIpQuery = new QueryWrapper<>();
            checkIpQuery.eq("ip", ip);
            Server ipCheck = serverService.getOne(checkIpQuery);
            if (!Objects.isNull(ipCheck)) {
                return SaResult.error("ip已存在: " + ip);
            }
        }

        server.setIp(String.join(",", server.getIpList()));
        server.setModule(String.join(",", server.getModuleList()));
        server.setCreatetime(new Date());
        serverService.save(server);
        return SaResult.data(server).setMsg("服务器信息添加成功！");
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "/searchServer", method = RequestMethod.GET)
    public SaResult searchServer(@RequestParam("Name") String name,
                                 @RequestParam("timeList") List<String> timeList,
                                 @RequestParam("pageSize") int pageSize,
                                 @RequestParam("pageNum") int pageNum) {

        // 特殊时段梳理
        List<String> availServer = new ArrayList<>();
        if (!timeList.isEmpty()) {
            List<String> serverAll = new ArrayList<>();

            // 获取所有服务器
            List<Server> serverList = serverService.list();
            for (Server s : serverList) {
                serverAll.add(s.getName());
            }
            // 获取包含该时间段任务的服务器
            List<String> serverUse = new ArrayList<>();
            for (String time : timeList) {
                QueryWrapper<ServerTask> taskUse = new QueryWrapper<>();
                taskUse.like("task_time", time);
                List<ServerTask> taskList = serverTaskService.list(taskUse);
                for (ServerTask task : taskList) {
                    if (!serverUse.contains(task.getServername())) {
                        serverUse.add(task.getServername());
                    }
                }
            }

            // 获取时间段可用的服务器
            for (String s : serverAll) {
                if (!serverUse.contains(s)) {
                    availServer.add(s);
                }

            }
        }
        QueryWrapper<Server> searchQuery = new QueryWrapper<>();
        if (!name.isEmpty()){
            searchQuery.like("name", name);
            searchQuery.or().like("ip", name);
        }

        if (!timeList.isEmpty()) {
            searchQuery.in("name", availServer);
        }

        Page<Server> page = new Page<>(pageNum, pageSize);
        page = serverService.page(page, searchQuery);

        // List<Server> serverList = serverService.list(searchQuery);

        for (Server serverOne : page.getRecords()) {
            List<String> ipList = new ArrayList<>();
            // 使用String的split方法按逗号分割ip字段，并添加到ipList中
            String[] ipParts = serverOne.getIp().split(",");
            for (String ipPart : ipParts) {
                ipList.add(ipPart.trim()); // 可能需要trim来去除空格
            }
            serverOne.setIpList(ipList);

            // 添加组件
            List<String> moduleList = new ArrayList<>();
            String[] moduleParts = serverOne.getModule().split(",");
            for (String modulePart : moduleParts) {
                 moduleList.add(modulePart.trim());
            }
            serverOne.setModuleList(moduleList);
        }

        JSONObject data = new JSONObject();
        data.put("data", page.getRecords());
        data.put("total", page.getTotal());

        return SaResult.data(data).setMsg("服务器信息查询成功！");
    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "/changeState", method = RequestMethod.POST)
    public SaResult changeState(@RequestBody Server server) {
        if (server == null) {
            return SaResult.error("信息不存在");
        }

        if (server.getState().equals(0)) {
            QueryWrapper<ServerTask> confirmQuery = new QueryWrapper<>();
            confirmQuery.eq("sid", server.getId());
            List<ServerTask> serverList = serverTaskService.list(confirmQuery);
            if (!CollectionUtils.isEmpty(serverList)) {
                return SaResult.error("服务器存在任务，无法禁用！");
            }
        }

        QueryWrapper<Server> changeQuery = new QueryWrapper<>();
        changeQuery.eq("id", server.getId());
        Server serverOne = serverService.getOne(changeQuery);
        if (!Objects.isNull(serverOne)) {
            int state = (server.getState() == 1) ? 0 : 1;
            serverOne.setState(state);
            if (serverService.updateById(serverOne)) {
                return SaResult.ok("服务器状态修改成功！");
            } else {
                return SaResult.error("服务器状态修改失败！");
            }
        }
        return SaResult.error("服务器不存在！");
    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "/delServer", method = RequestMethod.POST)
    public SaResult delServer(@RequestBody Server server) {
        if (server == null) {
            return SaResult.error("信息不存在");
        }

        QueryWrapper<ServerTask> delQuery = new QueryWrapper<>();
        delQuery.eq("sid", server.getId());
        List<ServerTask> serverList = serverTaskService.list(delQuery);
        if (!CollectionUtils.isEmpty(serverList)) {
            return SaResult.error("服务器存在任务，无法删除！");
        }

        return delete(serverService.removeById(server), "服务器");
    }
}
